﻿using CNKI.TPI.Web.Admin.IBLL;
using CNKI.TPI.Web.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Castle.DynamicProxy;
using CNKI.TPI.Web.Search.Model;
using System.Linq.Expressions;
using KNet.Data.Entity;
using System.Text;
namespace CNKI.TPI.Web.UI.Controllers.Admin
{
    public class Admin_SingleDBPublishController : BaseController
    {
        //
        // GET: /SingleDBPublish/

        ISingleDBPublishService singleService = null;
        public Admin_SingleDBPublishController(ISingleDBPublishService singleService)
        {
            this.singleService = generator.CreateInterfaceProxyWithTarget<ISingleDBPublishService>(singleService, new IInterceptor[] { new LogInterceptor() });
        }
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult SmilarIndex()
        {
            return View("SimilarDbList");
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        ///  
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Search(FormCollection form)
        {
            int pageIndexNow = 1;// 当前页    
            string type = "";
            string name = "";
            if (!String.IsNullOrEmpty(Request["pageIndexNow"]))
            {
                pageIndexNow = int.Parse(Request["pageIndexNow"]);
            }
            if (!String.IsNullOrEmpty(Request["type"]))
            {
                type = Request["type"].ToString();
            }
            if (!String.IsNullOrEmpty(Request["HiddenDbName"]))
            {
                name = Request["HiddenDbName"].ToString();
            }
            ViewBag.DBListALL = singleService.GetDBList(null);
            PageList(pageIndexNow, type, name, null);
            return PartialView("ResultList");
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult SearchSmilar(FormCollection form)
        {
            int pageIndexNow = 1;// 当前页    
            string type = "all";
            string name = "";
            if (!String.IsNullOrEmpty(Request["pageIndexNow"]))
            {
                pageIndexNow = int.Parse(Request["pageIndexNow"]);
            }
            if (!String.IsNullOrEmpty(Request["HiddenDbName"]))
            {
                name = Request["HiddenDbName"].ToString();
            }
            PageList(pageIndexNow, type, name, new List<SearchType>() { SearchType.TPI });
            return PartialView("SimilarResult");
        }

        private void PageList(int pageIndexNow, string type, string name, List<SearchType> searchtype)
        {
            int pageSize = 10;//每页显示记录数
            int sumPage = 0;//一共多少页
            int disPgae = 8;  //默认显示页数，当页数大于该数值时，按规定格式显示
            int count = 0;//总条数

            IList<SYS_CMS_DATABASE> list = singleService.GetDBListPageSize(pageIndexNow, pageSize, type, name, out count, searchtype);
            if (list != null && list.Count > 0)
            {
                ViewBag.DbList = list;
            }
            sumPage = count / pageSize; //一共多少页
            if (count % pageSize != 0)
            {
                sumPage = sumPage + 1;
            }
            ColumnAliasHelper com = new ColumnAliasHelper();
            ViewBag.TotalPage = sumPage;
            ViewBag.PageList = com.GetPageList(pageIndexNow, sumPage, disPgae);
            ViewBag.PageNow = pageIndexNow;//当前页
            ViewBag.PageSize = pageSize;
            ViewBag.Count = count;

        }
        /// <summary>
        /// 加载发布形式页面
        /// </summary>
        /// <param name="DbID"></param>
        /// <returns></returns>
        public ActionResult Config(string DbID)
        {
            ViewBag.DbID = DbID;
            SYS_CMS_DATABASE list = singleService.GetDatabaseByID(int.Parse(DbID));
            if (list != null)
            {
                ViewBag.DbCode = list.DatabaseCode;
                ViewBag.DbName = list.DatabaseName;
                ViewBag.PubFlage = list.DatabasePubFlag;
                ViewBag.VisibleFlage = list.VisibleFlag;
                ViewBag.TemplateID = list.TemplateID;
                ViewBag.Sort = list.OrderType;
            }
            IList<SYS_CMS_PUBLISHTYPE> publishList = singleService.GetTemplateList();
            if (list.SearchType != (int)SearchType.TPI)
            {
                int videoLibID = int.Parse(ConfigHelper.GetAppSettingsValue("VideoLibID"));
                int picLibID = int.Parse(ConfigHelper.GetAppSettingsValue("PicLibID"));
                int audioLibID = int.Parse(ConfigHelper.GetAppSettingsValue("AudioLibID"));
                int ebookLibID = int.Parse(ConfigHelper.GetAppSettingsValue("EBookLibID"));
                publishList = publishList.Where(c => (c.SysID != videoLibID && c.SysID != picLibID && c.SysID != audioLibID && c.SysID != ebookLibID)).ToList();
            }
            ViewBag.PublishType = publishList;
            return PartialView("Config");
        }
        /// <summary>
        /// 发布形式 保存
        /// </summary>
        /// <param name="DbID"></param>
        /// <param name="templateID"></param>
        /// <param name="visibleFlage"></param>
        /// <returns></returns>
        public bool TemplateSave(string DbID, string templateID, string visibleFlage, string DBSort)
        {
            bool flage = false;
            flage = singleService.UpdatetDBTemplate(DbID, templateID, visibleFlage, DBSort);
            return flage;

        }
        /// <summary>
        /// 取消发布
        /// </summary>
        /// <param name="DbID"></param>
        /// <returns></returns>
        public bool Cancel(string DbID)
        {
            bool flage = false;
            flage = singleService.UpdatetDBPubFlag(DbID, 0);
            return flage;

        }
        /// <summary>
        /// 从数据获取设置的字段信息
        /// </summary>
        /// <param name="DbID"></param>
        /// <param name="type"></param>
        private void ColumnInfo(string DbID, FieldType type)
        {
            ViewBag.DbID = DbID;
            SYS_CMS_DATABASE list = singleService.GetDatabaseByID(int.Parse(DbID));
            ViewBag.PubFlage = list.DatabasePubFlag;
            IList<SYS_CMS_DATABASE_FIELD> listField = singleService.GetDBField(list.DatabaseCode);
            ViewBag.ListField = listField;
            //if (list[0].DatabasePubFlag == 1)//修改模式，需获取已经设置的检索字段
            //{
            IList<SYS_CMS_DATABASE_PUBLISH_FIELD> listf = singleService.GetField(DbID, type);
            ViewBag.DiapList = listf;
            //显示名
            StringBuilder dispName = new StringBuilder();
            if (listf != null && listf.Count > 0)
            {
                dispName.Append('[');
                foreach (SYS_CMS_DATABASE_PUBLISH_FIELD item in listf)
                {
                    string str = "{\"name\":\"" + item.FieldName + "\",\"displayname\":\"" + item.FieldDispName + "\",\"displaywidth\":\"" + item.BriefWidth + "\"}";
                    dispName.Append(str).Append(',');
                }
                if (dispName != null)
                {
                    ViewBag.DispName = dispName.ToString().TrimEnd(',') + "]";
                }
                else
                {
                    ViewBag.DispName = "";
                }

                //}
            }
        }

        /// <summary>
        /// 初始化 设置检索字段页面
        /// </summary>
        /// <param name="DbID"></param>
        /// <returns></returns>
        public ActionResult SearchColumn(string DbID)
        {
            ColumnInfo(DbID, FieldType.Search);
            return View("SearchColumn");
        }
        /// <summary>
        /// 初始化 设置概览字段页面
        /// </summary>
        /// <param name="DbID"></param>
        /// <returns></returns>
        public ActionResult ViewColumn(string DbID)
        {
            ColumnInfo(DbID, FieldType.Overview);
            return View("ViewColumn");
        }
        /// <summary>
        /// 初始化 设置细缆字段页面
        /// </summary>
        /// <param name="DbID"></param>
        /// <returns></returns>
        public ActionResult DetialColumn(string DbID)
        {
            ColumnInfo(DbID, FieldType.Detail);
            return View("DetialColumn");
        }
        /// <summary>
        /// 初始化 设置细缆字段页面
        /// </summary>
        /// <param name="DbID"></param>
        /// <returns></returns>
        public ActionResult SortColumn(string DbID)
        {
            ColumnInfo(DbID, FieldType.Sort);
            return View("SortColumn");
        }
        public ActionResult PublishOver(string DbID)
        {
            SYS_CMS_DATABASE list = singleService.GetDatabaseByID(int.Parse(DbID));
            ViewBag.DbCode = list.DatabaseCode;
            ViewBag.DbName = list.DatabaseName;
            return View("PublishOver");
        }

        /// <summary>
        /// 保存显示名称
        /// </summary>
        /// <param name="DbID"></param>
        /// <param name="Name"></param>
        /// <param name="DisplayName"></param>
        /// <returns></returns>
        public bool SaveDispName(string DbID, string Name, string DisplayName)
        {
            bool flage = false;
            flage = singleService.UpdatetDBDisplayName(DbID, Name, DisplayName);
            return flage;

        }
        /// <summary>
        /// 保存设置的字段
        /// </summary>
        /// <param name="DbID"></param>
        /// <param name="Column"></param>
        /// <param name="flage"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private bool ColumnSave(string DbID, string Column, string flage, int type)
        {
            bool m = false;
            IList<SYS_CMS_DATABASE_PUBLISH_FIELD> list = new List<SYS_CMS_DATABASE_PUBLISH_FIELD>();
            if (Column != "")
            {
                string[] columnArray = Column.Split(',');
                foreach (string str in columnArray)
                {
                    SYS_CMS_DATABASE_PUBLISH_FIELD obj = new SYS_CMS_DATABASE_PUBLISH_FIELD();
                    string[] stritem = str.Split('#');
                    obj.DbID = DbID;
                    obj.FieldType = type.ToString();
                    obj.FieldName = stritem[0];
                    obj.FieldProperty = 0;
                    obj.BriefWidth = stritem[2];
                    obj.FieldDispName = stritem[1];
                    list.Add(obj);
                }
                m = singleService.PublicField(DbID, list, flage);
            }
            return m;

        }
        /// <summary>
        /// 保存检索字段
        /// </summary>
        /// <param name="DbID"></param>
        /// <param name="Column"></param>
        /// <param name="flage"></param>
        /// <returns></returns>
        public bool SearchColumnSave(string DbID, string Column, string flage)
        {
            bool m = false;
            int type = (int)FieldType.Search;
            m = ColumnSave(DbID, Column, flage, type);
            return m;
        }
        /// <summary>
        /// 保存概览字段
        /// </summary>
        /// <param name="DbID"></param>
        /// <param name="Column"></param>
        /// <param name="flage"></param>
        /// <returns></returns>
        public bool ViewColumnSave(string DbID, string Column, string flage)
        {
            bool m = false;
            int type = (int)FieldType.Overview;
            m = ColumnSave(DbID, Column, flage, type);
            return m;
        }
        /// <summary>
        /// 保存细缆字段
        /// </summary>
        /// <param name="DbID"></param>
        /// <param name="Column"></param>
        /// <param name="flage"></param>
        /// <returns></returns>
        public bool DetialColumnSave(string DbID, string Column, string flage)
        {
            bool m = false;
            int type = (int)FieldType.Detail;
            m = ColumnSave(DbID, Column, flage, type);
            return m;
        }
        /// <summary>
        ///保存排序字段
        /// </summary>
        /// <param name="DbID"></param>
        /// <param name="Column"></param>
        /// <param name="flage"></param>
        /// <returns></returns>
        public bool SortColumnSave(string DbID, string Column, string flage)
        {
            bool m = false;
            int type = (int)FieldType.Sort;
            m = ColumnSave(DbID, Column, flage, type);
            if (m == true)
            {
                m = singleService.UpdatetDBPubFlag(DbID, 1);
            }
            return m;
        }
        /// <returns></returns>
        public bool CreateDrsXml()
        {
            DRSManager drsm = new DRSManager();
            return drsm.UpdateDRSInfo();

        }
        /// <summary>
        /// 更新数据库排序
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public bool UpdateDBSort(IList<SYS_CMS_DATABASE> list)
        {
            return singleService.UpdateDBSort(list);
        }

        public ActionResult SetSimilarDb(string DbCode, string DbName, int DbID)
        {
            ViewBag.DbCode = DbCode;
            ViewBag.DbName = DbName;
            //IList<SYS_CMS_DATABASE> Dblist = singleService.GetDBList(new List<SearchType>() { SearchType.TPI });//获取数据库列表
            IList<SYS_CMS_DATABASE> Dblist = singleService.GetDBList();//获取数据库列表
            ViewBag.Dblist = Dblist;

            string thisoptionselect = "";
            IList<SYS_CMS_DATABASE_FIELD> FieldList = singleService.GetDBField(DbCode);
            IList<SYS_CMS_DATABASE_FIELD> ThisDbFieldList = new List<SYS_CMS_DATABASE_FIELD>();
            if (FieldList != null)
            {
                foreach (SYS_CMS_DATABASE_FIELD item in FieldList)
                {
                    if (!item.Field.StartsWith("SYS_"))
                    {
                        ThisDbFieldList.Add(item);
                        thisoptionselect += "<option value=" + item.Field + ">" + item.Field + "</option>";
                    }
                    else if (item.Field.Equals("SYS_FLD_VSM"))
                    {
                        ThisDbFieldList.Add(item);
                        thisoptionselect += "<option selected=selected  disabled=disabled value=" + item.Field + ">" + item.Field + "</option>";
                    }
                }
            }
            ViewBag.ThisOptionSelect = thisoptionselect;
            ViewBag.ThisDbFieldList = ThisDbFieldList;

            IList<SYS_CMS_DATABASE_RELATION> RelationDblist = singleService.GetDbRelation(DbCode);//获取已设置的关联数据库字段
            ViewBag.RelationDbList = RelationDblist;
            return View("SetSimilarDb");
        }
        public string GetFieldString(string dbcode)
        {
            string optionselect = "";
            int vsmselect = 0;
            IList<SYS_CMS_DATABASE_FIELD> fieldlist = singleService.GetDBField(dbcode);
            if (fieldlist != null)
            {
                foreach (SYS_CMS_DATABASE_FIELD item in fieldlist)
                {
                    if (!item.Field.StartsWith("SYS_") )
                    {
                        optionselect += "<option value=" + item.Field + ">" + item.Field + "</option>";
                    }
                    else if(item.Field.Equals("SYS_FLD_VSM"))
                    {
                        vsmselect = 1;
                        optionselect += "<option selected=selected value=" + item.Field + ">" + item.Field + "</option>";
                    }

                }
            }
            return "[{\"msg\":\"" + optionselect + "\",\"vsmselect\":\"" + vsmselect + "\"}]"; //下拉列表 html串
        }
        public bool SaveRelation(IList<SYS_CMS_DATABASE_RELATION> list)
        {
            return singleService.SaveRelationField(list);
        }
        public bool DelRelation(string dbcode)
        {
            return singleService.DeleteRelation(dbcode);
        }
    }
}
